package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Teacher;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class OtherTeacherDao01 implements BaseTeacherDao {
    private static ArrayList<Teacher> teachers = new ArrayList<>();


    static {
        try {
            FileReader fr = new FileReader("itheima-edu-info-manager\\tea.txt");
            int len;
            char[] chars = new char[1024];
            StringBuilder sb = new StringBuilder();
            while ((len = fr.read(chars)) != -1) {
                sb.append(new String(chars, 0, len));
            }
            String str = sb.toString();
            String[] split = str.split(System.lineSeparator());
            for (int i = 0; i < split.length; i++) {
                String s = split[i];
                String[] split1 = s.split(",");
                Teacher teacher = new Teacher(split1[0], split1[1], split1[2], split1[3]);
                //System.out.println(teacher);
                teachers.add(teacher);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean addTeacher(Teacher teacher) {
        boolean add = teachers.add(teacher);
        reSave();
        return add;

    }

    public Teacher[] findAllTeacher() {
        Teacher[] teacher = new Teacher[teachers.size()];
        for (int i = 0; i < teachers.size(); i++) {
            Teacher teacher1 = teachers.get(i);
            teacher[i] = teacher1;
        }
        return teacher;
    }

    public void deleteTeacher(String sid) {
        int index = getIndex(sid);
        teachers.remove(index);
        reSave();
    }


    public void updateTeacher(String sid, Teacher teacher) {
        int index = getIndex(sid);
        teachers.set(index, teacher);
        reSave();
    }


    public int getIndex(String sid) {
        int index = -1;
        Teacher[] t = new Teacher[teachers.size()];
        Teacher[] tea = OtherTeacherDao01.teachers.toArray(t);
        for (int i = 0; i < tea.length; i++) {
            Teacher teacher = tea[i];
            if (teacher != null && sid.equals(teacher.getSid())) {
                index = i;
            }
        }
        return index;
    }

    public void reSave() {
        try {
            FileWriter fw = new FileWriter("itheima-edu-info-manager\\tea.txt");
            for (Teacher teacher : teachers) {
                String str = teacher.toString();
                fw.write(str);
                fw.write(System.lineSeparator());
                fw.flush();
            }
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
